import os from 'node:os'
import { md5 } from '../utils/encrypt.js'
import { Router } from '../utils/router.js'
import logger from '../utils/logger.js'
import { User } from '../db/pojo/user.js'
import { userDao } from '../db/dao/user.js'
import { ERROR_CODE } from '../../constant.js'
import NodeURL from 'node:url'
import { v4 } from 'uuid'
import fs from 'node:fs'
import path from 'node:path'

const router = new Router()

router.get('/api/v1/rest/system/state', () => {
    return {
        error: 0,
        data: {
            hostname: os.hostname(),
            platform: os.platform(),
            uptime: os.uptime(),
            cpus: os.cpus(),
            loadavg: os.loadavg(),
            freemem: os.freemem(),
            totalmem: os.totalmem()
        },
        message: '获取系统状态成功'
    }
})

router.post('/api/v1/rest/users/register', async (request) => {
    try {
        // const decrypted = decrypt(data, generateKey(key))
        // logger.info(`decrypted: ${JSON.stringify(decrypted)}`)
        const body = await request.body() || {}
        const { account, password, email, age } = body
        logger.info('body is: ', body)
        logger.info('params: ', account, password, email, age)
        if (!account || !password) {
            return {
                error: ERROR_CODE.CLIENT_ERROR,
                message: 'account or password required!'
            }
        }
        const accountExisted = userDao.queryWithConditions([`account = '${account}'`])
        if (accountExisted.length > 0) {
            return {
                error: ERROR_CODE.USER_EXISTS,
                message: '用户已存在'
            }
        }
            
        const user = new User({
            id: v4(),
            account,
            password: md5(password),
            email,
            age
        })
        const id = userDao.insert(user)

        return {
            error: 0,
            data: { userId: id },
            message: '用户注册成功'
        }
    } catch (error) {
        logger.error(error)
        return {
            error: ERROR_CODE.SERVER_ERROR,
            message: error.message
        }
    }
})

router.get('/api/v1/rest/users/:username', async (request, response) => {
    const { pathname } = NodeURL.parse(request.url)
    const account = pathname.split('/').at(-1)
    const user = userDao.queryWithConditions([`account = '${account}'`])
    logger.info(`query user info`, user)

    if (user.length > 0) {
        const [data] = user
        delete data.password
        return {
            error: 0,
            data,
            message: '查询成功'
        }
    } else {
        response.status(404)
        return {
            error: ERROR_CODE.CLIENT_ERROR
        }
    }
})

router.post('/api/v1/rest/users/export', async (request, response) => {
    const allUserData = userDao.query().map(user => {
        delete user.password
        return user
    })
    logger.info('query all users: ', allUserData)
    const fileContent = JSON.stringify(allUserData, null, 4)
    const filePath = path.join(process.cwd(), '/static/user.json')
    const stream = fs.createWriteStream(filePath, 'utf-8')
    stream.end(fileContent)

    stream.on('finish', () => {
        response.json({
            error: 0,
            data: {
                filePath
            },
            message: '用户数据导出成功'
        })
    })

    stream.on('error', (error) => {
        response.json({
            error: ERROR_CODE.SERVER_ERROR,
            message: error.message
        })
    })
})

export default router
